package angry.courses.servlets;

import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

import javax.servlet.ServletException;

public class AuthenticateServlet extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		final String returnUrl = req.getParameter("return");

		res.setContentType("text/html");
		PrintWriter out = res.getWriter();

		out.println(new HtmlFormatter() {
			public String title() {
				return "Credentials";
			}

			public void body(StringBuffer buf) {
				buf.append(heading(3, "Enter your credentials:"));
				buf.append("<form method=\"post\" action=\"Authenticate" +
					"?return=" + returnUrl + "\" >");
				buf.append("<table>");
				buf.append(tr("Name: ", textbox("name")));
				buf.append(tr("Reg Nr.: ", textbox("regnr")));
				buf.append("</table>");
				buf.append(button("Submit"));
				buf.append("</form>");
			}
		}.htmlTag());
		out.close();
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		final String returnUrl = req.getParameter("return");
		final String name = req.getParameter("name");
		final String regnr = req.getParameter("regnr");
	
		StudentDelegate studentDelegate = new StudentDelegate();
	
		if (studentDelegate.validateStudent(name, regnr)) {
			String redirectURL =
				res.encodeRedirectURL(returnUrl + "?name=" +
					name + "&regnr=" + regnr);
			res.sendRedirect(redirectURL);
		} else {
			res.setContentType("text/html");
			PrintWriter out = res.getWriter();
			out.println(new HtmlFormatter() {
				public String title() {
					return "Credentials";
				}

				public void body(StringBuffer buf) {
					buf.append(heading(3, "<font color=\"#cc1100\">" + 
						"Invalid Credentials!</font>"));
					buf.append("Could not find your name or<br>" +
						"your registration number is incorrect.<br>");
					buf.append(link("Try again",
						"Authenticate?return=" + returnUrl));
					buf.append(" or " + link("Go back", "index.html"));
				}
			}.htmlTag());
			out.close();
		}
    }
}
